﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Web.UI;
using System.IO;
using System.Xml;
using System.Net;
using LiUTrading.Models;
namespace LiUTrading.Controllers
{

    public class AccountController : Controller
    {
        private UserRepository userRepository = new UserRepository();
        private const string CASHOST = "https://login.liu.se/cas/";
        //
        // GET: /Account/

        public ActionResult Index()
        {
            return PartialView();
        }
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            string tkn = Request.QueryString["ticket"];
            string service = Request.Url.GetLeftPart(UriPartial.Path);
            if (tkn == null || tkn.Length == 0)
            {
                string redir = CASHOST + "login?" + "service=" + service;

                Response.Redirect(redir);
                   
                return View();
            }
            string validateUrl = CASHOST + "serviceValidate?" + "ticket=" + tkn + "&" + "service=" + service;
            StreamReader Reader = new StreamReader(new WebClient().OpenRead(validateUrl));
            string resp = Reader.ReadToEnd();

            NameTable nt = new NameTable();
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
            XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
            XmlTextReader reader = new XmlTextReader(resp, XmlNodeType.Element, context);
            string netid = null;

            // A very dumb use of XML. Just scan for the "user". If it isn't there, its an error.
            while (reader.Read())
            {
                if (reader.IsStartElement())
                {
                    string tag = reader.LocalName;
                    if (tag == "user")
                        netid = reader.ReadString();
                }
            }
            // if you want to parse the proxy chain, just add the logic above
            reader.Close();
            // If there was a problem, leave the message on the screen. Otherwise, return to original page.
            if (netid == null)
            {
                ViewData["Text"] = "CAS returned to this application, but then refused to validate your identity.";

            }
            else
            {
                User user = userRepository.GetUser(netid);
                FormsAuthentication.RedirectFromLoginPage(netid, false);
                if (user == null)
                {                  
                    return RedirectToAction("AddUser");
                }
                else
                {
                    ViewData["Text"] = "Welcome " + netid;
                    return RedirectToAction("Index", "Home");
                }

            }
            return View("Error");
        }
        //Get : /Account/AddUser
        // [Authorize]
        public PartialViewResult AddUser()
        {
            User user = new User()
            {
                LiuID = User.Identity.Name
            };
            return PartialView(user);
        }

        //POST Account/AddUser
        [HttpPost]
        public ActionResult AddUser(User user)
        {
            if (ModelState.IsValid)
            {
                if (TryUpdateModel(user))
                {
                    userRepository.Add(user);
                    userRepository.Save();
                    return RedirectToAction("Index","Home");
                }
            }
            return PartialView(user);
        }
        [Authorize]
        public ActionResult Details()
        {
            string liuId = User.Identity.Name;
            User user = userRepository.GetUser(liuId);
            if (user == null)
            {
                return PartialView("Error");
            }
            else
            {
                return PartialView(user);
            }
        }



        //GET Account/Edit
        [Authorize]
        public ActionResult Edit(int id)
        {
            User user = userRepository.GetUser(id);
            if (user == null)
            {
                return PartialView("AddUser");
            }
            else
            {
                return PartialView(user);
            }
        }
        //Post: /Account/Edit/
        [HttpPost, Authorize]
        public ActionResult Edit(User user)
        {
            if (ModelState.IsValid)
            {
                User userDb = userRepository.GetUser(user.UserId);
                userDb.PhoneNumber = Request.Form["PhoneNumber"];
                userDb.LastName = Request.Form["LastName"];
                userDb.FirstName = Request.Form["FirstName"];
                userDb.Address = Request.Form["Address"];
                
                userRepository.Save();
                return Json(new { success = true });
             //   return RedirectToAction("Details");

            }
            return PartialView(user);
        }


        //Get /Account/MyPage
        public ActionResult MyPage()
        {
            return PartialView();
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

    }
}
